"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '18/10/2024'
    comment: 极光推送相关
"""
import base64
import aiohttp
from curl_cffi import requests

from config import Config
from project.core.exception import BizError
from project.lib.common import logger
from project.core.log import Colors


class JPush:

    host_device = "https://device.jpush.cn"
    host = 'https://api.jpush.cn'

    @staticmethod
    def get_headers():
        """
        """
        auth_str = f"{Config.JPUSH_OPTIONS['app_key']}:{Config.JPUSH_OPTIONS['app_secret']}"
        bs = base64.b64encode(auth_str.encode("utf-8"))
        return {
            "Authorization": "Basic " + bs.decode("utf-8")
        }

    @classmethod
    async def send_async(cls, registration_id, content, title):
        """
        """
        url = f'{cls.host}/v3/push'

        payload = {
            # 必填
            "platform": "all",
            # 必填
            "audience": {"registration_id": [registration_id]},
            "notification": {
                "android": {
                    "alert": content,
                    "title": title,
                    "intent": {
                        "url": "intent:#Intent;component=com.udi.camellia/com.udi.camellia.MainActivity;end"
                    },
                },
                "ios": {
                    "alert": content,
                    "sound": "default",
                    "badge": "+1"
                }
            }
        }

        logger.info(f'开始极光推送 registration_id: {registration_id} title: {title} content: {content}', font_color=Colors.PURPLE.value)
        async with aiohttp.ClientSession() as session:
            async with session.post(url, headers=cls.get_headers(), json=payload) as resp:
                if resp.status != 200:
                    error = f'极光推送失败 url: {url} status: {resp.status} content: {(await resp.content.read())}'
                    logger.error(message=error)
                    raise BizError(message=error)

                result = await resp.json()

                return result

    @classmethod
    def send(cls, registration_id, content, title=''):
        """
        """
        url = f'{cls.host}/v3/push'

        payload = {
            # 必填
            "platform": "all",
            # 必填
            "audience": {"registration_id": [registration_id]},
            "notification": {
                "android": {
                    "alert": content,
                    "title": title,
                    "intent": {
                        "url": "intent:#Intent;component=com.udi.camellia/com.udi.camellia.MainActivity;end"
                    },
                },
                "ios": {
                    "alert": content,
                    "sound": "default",
                    "badge": "+1"
                }
            }
        }

        logger.info(f'开始极光推送 registration_id: {registration_id} title: {title} content: {content}', font_color=Colors.PURPLE.value)
        resp = requests.post(url, headers=cls.get_headers(), json=payload)
        if resp.status_code != 200:
            error = f'极光推送失败 url: {url} status: {resp.status_code} content: {resp.content}'
            logger.error(message=error)

        return resp.json()

    @classmethod
    async def get_registration_async(cls, registration_id):
        """
        """
        url = f"{cls.host_device}/v3/devices/{registration_id}"

        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers=cls.get_headers()) as resp:
                if resp.status != 200:
                    raise BizError(f'极光请求失败 url: {url} status: {resp.status} content: {(await resp.content.read())}')

                result = await resp.json()

                return result

    @classmethod
    def get_registration(cls, registration_id):
        """
        """
        url = f"{cls.host_device}/v3/devices/{registration_id}"

        resp = requests.get(url, headers=cls.get_headers())
        if resp.status_code != 200:
            raise BizError(f'极光请求失败 url: {url} status: {resp.status_code} content: {resp.content}')

        return resp.json()


if __name__ == "__main__":
    """
    """
    # JPush.send('test', 'title', 'content')

    JPush.send('1104a897939fd6bd603', 'test', 'test')





